import { defineStore } from 'pinia';

export const useQuarterHistoryStore = defineStore('quarterhistory', () => {
  const quarterList = ref<any[]>([]);
  function filterAndDeduplicate(data: any[]): any[] {
    const uniqueYearMonths = new Set<string>();
    const result: { yearMonth: string }[] = [];
    data.forEach((item) => {
      if (item.yearMonth && !uniqueYearMonths.has(item.yearMonth)) {
        result.push(item);
        uniqueYearMonths.add(item.yearMonth);
      }
    });
    return result;
  }
  function convertYearMonthFormat(data: { yearMonth: string }[]): { yearMonth: string }[] {
    const result: { yearMonth: string }[] = [];
    data.forEach((item) => {
      result.push({ yearMonth: item.yearMonth });
    });
    return result;
  }
  function removeDuplicates(data: any[]): any[] {
    const seen = new Set<string>();
    const result: any[] = [];

    data.forEach((item) => {
      if (!seen.has(item.yearMonth)) {
        seen.add(item.yearMonth);
        result.push(item);
      }
    });

    return result;
  }
  const getQuarterList = async () => {
    const data = ref<any[]>([]);
    await getQuarterHistoryCountyIndicatorlist().then((res: any) => {
      data.value = res.data;
    });
    // 处理数据
    const list = ref<any[]>([]);
    for (let i = 0; i < data.value.length; i++) {
      list.value.push({ yearMonth: data.value[i].yearMonth });
    }
    list.value = filterAndDeduplicate(list.value);
    list.value = convertYearMonthFormat(list.value);
    quarterList.value = removeDuplicates(list.value);
  };
  return {
    quarterList,
    getQuarterList,
  };
});
